﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using Coticula.Web.Models;

namespace Coticula.Web.Controllers
{ 
    public class SubmitController : Controller
    {
        private readonly CoticulaDbContext _db = new CoticulaDbContext();

        //
        // GET: /Submit/

        [Authorize]
        public ViewResult Index(int? id)
        {
            ViewBag.LanguageId = new SelectList(_db.Languages, "Id", "Name", 1);

            int selectedValue = 1;
            if (id != null && id != 0) selectedValue = (int)id;
            ViewBag.ProblemId = new SelectList(_db.Problems, "Id", "Name", selectedValue);

            var model = new Solutions();
            model.DateTime = DateTime.Now;
            return View(model);
        }

        //
        // POST: /Submit/Index

        [HttpPost]
        [Authorize]
        [ValidateInput(false)]
        public ActionResult Index(Solutions solution)
        {
            if (ModelState.IsValid)
            {
                if (_db.Problems.Find(solution.ProblemId) == null)
                {
                    ModelState.AddModelError("ProblemId", "Can't find this problem.");
                }
                else if (_db.Languages.Find(solution.LanguageId) == null)
                {
                    ModelState.AddModelError("LanguageId", "Can't find this language.");
                }
                else
                {
                    solution.UserId = (int)Membership.GetUser().ProviderUserKey;
                    var result = new Results { Solution = solution };
                    _db.Results.Add(result);
                    _db.SaveChanges();
                    return RedirectToAction("Index", "Solution");
                }
            }

            ViewBag.ProblemId = new SelectList(_db.Problems, "Id", "Name", solution.ProblemId);
            ViewBag.LanguageId = new SelectList(_db.Languages, "Id", "Name", solution.LanguageId);
            return View(solution);
        }

        protected override void Dispose(bool disposing)
        {
            _db.Dispose();
            base.Dispose(disposing);
        }
    }
}